﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MethodWorx.CMS.Plugins.ContentTree;
using MethodWorx.CMS.Services;
using MethodWorx.CMS.Plugins.ActionResults;
using System.Web.Mvc;
using MethodWorx.CMS.Administration;
using System.Web;
using MethodWorx.CMS.Content;
using MethodWorx.CMS.Web;

namespace MethodWorx.CMS.Plugins.ContentManagement
{
    [CmsPlugin(Name = "Content Management", Description = "Manages Content", Id = "{25B6B8E6-9DD3-447B-8497-B3D86D08C7A2}")]
    public class ContentManagementExtension : Plugin, IContentTreePlugin
    {
        public IEnumerable<TreeNode> GetTreeNodes(string objectType, Guid? objectId)
        {
            //  get the content service
            ContentService service = new ContentService(this.CmsDataProvider);

            if (string.IsNullOrEmpty(objectType) && objectId == null)
            {
                yield return new TreeNode()
                {
                    ObjectType = "Pages",
                    Title = "Pages / Content",
                    Icon = "~/images/icons/folder.png",
                    Closed = true,
                    ToolbarButtons = new ToolbarButton[]
                        {
                            new ToolbarButton()
                            {                                
                                Icon = "~/images/icons/page_add.png",
                                Id = "CreateRootPage",
                                Title = "Create Root Page"                            
                            }
                        }
                };
            }
            else if(objectType == "Pages" && objectId == null)
            {
                //
                //  ok, we want root
                var page = service.GetRootPage();
                if (page != null)
                {
                    yield return GetTreeNodeFromPage(page, true);
                }
            }
            else if (objectType == "Page" && objectId.HasValue)
            {
                //
                //  ok, great, lets get the children
                var parent = service.GetPageById(objectId.Value);
                if (parent != null)
                {
                    foreach (var page in parent.ChildPages)
                    {
                        yield return GetTreeNodeFromPage(page, false);
                    }
                    Dictionary<ContentTemplate, int> templates = new Dictionary<ContentTemplate,int>();
                    foreach (var content in parent.ChildContent)
                    {
                        if (templates.ContainsKey(content.Template))
                            templates[content.Template]++;
                        else
                            templates.Add(content.Template, 1);
                    }

                    foreach (var contentTemplate in templates)
                    {
                        yield return GetTreeNodeFromContentTemplate(parent, contentTemplate.Key, contentTemplate.Value);
                    }
                }
            }
        }

        private TreeNode GetTreeNodeFromContentTemplate(Page page, ContentTemplate content, int count)
        {
            return new TreeNode()
            {
                Closed = true,
                Icon = "~/images/icons/content.png",
                ObjectId = content.Id,
                ObjectType = "ContentTemplate:" + page.Id,
                Title = content.Name + " (" + count + ")",
                DefaultAction = "EditContent",
                ToolbarButtons = new ToolbarButton[]
                        {
                            new ToolbarButton()
                            {
                                Icon = "~/images/icons/page_edit.png",
                                Id = "EditContent",
                                Title = "Edit Content",
                                ContextText = "Content: " + page.Path + "/" + content.Name
                            },
                            new ToolbarButton()
                            {
                                Icon = "~/images/icons/content_add.png",
                                Id = "CreateContent",
                                Title = "Create " + content.Name
                            }
                        }
            };
        }

        private TreeNode GetTreeNodeFromPage(Page page, bool root)
        {
            return new TreeNode()
                       {
                           Closed = true,
                           Icon = GetPageImage(page),
                           ObjectId = page.Id,
                           ObjectType = "Page",
                           Title = page.Name + ((root) ? " (Root)" : ""),
                           DefaultAction = "EditPage",
                           ToolbarButtons = new ToolbarButton[]
                                                {
                                                    new ToolbarButton()
                                                        {
                                                            Icon = "~/images/icons/page_add.png",
                                                            Id = "CreatePage",
                                                            Title = "Create Page"
                                                        },
                                                    new ToolbarButton()
                                                        {
                                                            Icon = "~/images/icons/page_edit.png",
                                                            Id = "EditPage",
                                                            Title = "Edit Page",
                                                            ContextText = "Page: " + page.Path
                                                        },
                                                    new ToolbarButton()
                                                        {
                                                            Icon = "~/images/icons/content_add.png",
                                                            Id = "CreateContent",
                                                            Title = "Create Content"
                                                        },
                                                    new ToolbarButton()
                                                        {
                                                            Icon = "~/images/icons/asterisk_orange.png",
                                                            Id = "PublishPage",
                                                            Title = "Publish"
                                                        }
                                                },
                           MenuItems = new TreeNodeMenuItem[]
                                           {
                                               new TreeNodeMenuItem()
                                                   {
                                                       Action = "PublishPage",
                                                       Id = "PublishPage",
                                                       Title = "Publish"
                                                   },
                                               new TreeNodeMenuItem()
                                                   {
                                                       Action = "DeletePage",
                                                       Id = "DeletePage",
                                                       Title = "Delete",
                                                       Confirm =
                                                           "Are you sure you want to delete this page?  All child pages and child content status will be set to [Awaiting Delete].  Once the page is published any child content and pages will be set to [Deleted]."
                            },
                        }
            };
        }

        private string GetPageImage(Page page)
        {
            if(page.Status == ContentStatus.AwaitingDelete ||
               page.Status == ContentStatus.PublishedAndAwaitingDelete)
                return "~/images/icons/page_awaitingdelete.png";
            else
                return "~/images/icons/page.png";
        }

        public ActionResult InvokeAction(string action, string objectType, Guid? objectId)
        {
            ContentService service = new ContentService(this.CmsDataProvider);
            ApplicationTypeService app = new ApplicationTypeService(this.CmsDataProvider);

            if (action == "CreateRootPage" && objectType == "Pages")
            {
                return new OpenDialogResult(UrlResolver.CreatePageUrl(), "Create Root Page");
            }
            else if (action == "CreatePage" && objectType == "Page" && objectId.HasValue)
            {
                return new OpenDialogResult(UrlResolver.CreatePageUrl(objectId.Value), "Create Page");
            }
            else if (action == "CreateContent" && objectType == "Page" && objectId.HasValue)
            {
                return new OpenDialogResult(UrlResolver.CreateContentItemUrl(objectId.Value), "Content Content");
            }
            else if (action == "EditContent" && objectType.StartsWith("ContentTemplate:") && objectId.HasValue)
            {
                var page = service.GetPageById(Guid.Parse(objectType.Replace("ContentTemplate:", "")));
                if(page != null)
                    return GetTabsForPage(page);
            }
            else if (action == "EditPage" && objectType == "Page" && objectId.HasValue)
            {
                var page = service.GetPageById(objectId.Value);
                if (page != null)
                    return GetTabsForPage(page);
            }
            else if(action == "PublishPage" && objectType == "Page" && objectId.HasValue)
            {
                var page = service.GetPageById(objectId.Value);
                if (page != null)
                    return new OpenDialogResult("~/Application/PublishPage/PublishOptions/" + page.Id, "Publish: " + page.Name);
            }
            else if (action == "DeletePage" && objectType == "Page" && objectId.HasValue)
            {
                var page = service.GetPageById(objectId.Value);
                if (page != null)
                    service.DeletePage(page);

                return new RefreshTreeNodeResult(true);
            }
            return new EmptyResult();
        }

        private static ActionResult GetTabsForPage(Page page)
        {
                    //
                    //  ok, go for it
            return new TabResult(
                "Preview",
                UrlHelper.GenerateContentUrl("~/content/preview/", new HttpContextWrapper(HttpContext.Current)) +
                page.Id,
                "Template",
                UrlHelper.GenerateContentUrl(UrlResolver.TemplateEditor(page.Template.Id),
                                             new HttpContextWrapper(HttpContext.Current)),
                "Workflow",
                UrlHelper.GenerateContentUrl("~/Page/EditWorkflow/", new HttpContextWrapper(HttpContext.Current)) +
                page.Id,
                "Page Properties",
                UrlHelper.GenerateContentUrl("~/Page/Properties/", new HttpContextWrapper(HttpContext.Current)) +
                page.Id,
                "Content Properties",
                UrlHelper.GenerateContentUrl("~/Content/Edit/", new HttpContextWrapper(HttpContext.Current)) + page.Id,
                "System",
                UrlHelper.GenerateContentUrl("~/Page/System/", new HttpContextWrapper(HttpContext.Current)) + page.Id);
        }
    }
}
